/*
 * @Author: szx
 * @Date: 2022-05-24 13:15:38
 * @LastEditTime: 2022-05-24 13:27:05
 * @Description:
 * @FilePath: \leetcode\面试题\08\10i\10.js
 */
/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} newColor
 * @return {number[][]}
 */
 var floodFill = function (image, sr, sc, newColor) {
    const dirs = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];
    const m = image.length,
        n = image[0].length;
    const target = image[sr][sc];
    const used = new Array(m).fill(0).map(() => new Array(n).fill(false));
    const dfs = (row, col) => {
        used[row][col] = true;
        image[row][col] = newColor;
        for (let dir of dirs) {
            const x = dir[0] + row,
                y = dir[1] + col;
            if (x >= 0 && x < m && y >= 0 && y < n && target == image[x][y] && !used[x][y]) {
                dfs(x, y);
            }
        }
    };
    dfs(sr, sc);
    return image;
};

